<?php

define('BENCH_DIR', dirname(__FILE__));

$conf = require_once(BENCH_DIR."/configs/bench.php");
require_once BENCH_DIR."/lib.php";
$vars = array();
$vars["conf"] = $conf;
$vars["benches"] = &$conf["benches"];

if(empty($_GET["bench"])) {
	$smarty = require_once(BENCH_DIR."/configs/smarty.php");
	if(!empty($_GET["code"])) {
		if(Util::isBenchExists($_GET["code"])) {
			echo Util::highlightFile($_GET["code"]);
			die();
		} else {
			die("File not found");
		}
	}
	if(!empty($_GET["clean"])) {
		if(Util::isBenchExists($_GET["clean"])) {
			Util::removeTemp($_GET["clean"]);
			header("Location: ?bench=".$_GET["clean"]);
			die();
		}
	}
	$smarty->assign($vars);
	$smarty->assign("title", "Main");
	$smarty->displayPage("home.tpl");
} else {
	if(!isset($conf["benches"][ $_GET["bench"] ])) {
		$conf["benches"][ $_GET["bench"] ] = array("name" => $_GET["bench"], "php" => 5);
	}
	$bench_meta = &$conf["benches"][ $_GET["bench"] ];
	if(file_exists(BENCH_DIR."/benches/".$_GET["bench"].".php")) {
		$bench = include(BENCH_DIR."/benches/".$_GET["bench"].".php");
		$bench = $bench_meta + $bench;
		$bench["code"] = $_GET["bench"];
		if(empty($bench)) {
			$smarty = require_once(BENCH_DIR."/configs/smarty.php");
			$smarty->assign($vars);
			$smarty->assign("error", "Returned invalid bench data (file must return array with code)");
			$smarty->displayPage("bench-error.tpl");
		}
	} else {
		$smarty = require_once(BENCH_DIR."/configs/smarty.php");
		$smarty->assign($vars);
		$smarty->displayPage("bench-not-found.tpl");
	}
	
	Util::prepareBench($bench);
	if(Util::isBenchExists($_GET["bench"])) {
		$vars["result"]= Util::getBenchResult($_GET["bench"]);
	} else {
		if(Util::createBenchCode($_GET["bench"], $bench)) {
			if(!Util::syntaxCheck($_GET["bench"], $error)) {
				$smarty = require_once(BENCH_DIR."/configs/smarty.php");
				$smarty->assign($vars);
				$smarty->assign("error", $error);
				$smarty->displayPage("bench-error.tpl");
			} else {
				$vars["result"] = Util::getBenchResult($_GET["bench"]);
			}
		} else {
			$smarty = require_once(BENCH_DIR."/configs/smarty.php");
			$smarty->assign($vars);
			$smarty->displayPage("bench-no-code.tpl");
		}
	}
	if(isset($_GET["json"])) {
		echo json_encode($vars["result"]);
		die();
	} else {
		$smarty = require_once(BENCH_DIR."/configs/smarty.php");
		$smarty->assign($vars);
		$smarty->assign_by_ref("bench", $bench);
		$smarty->displayPage();
	}
}

?>
